#!/usr/bin/python
import os
import sys

# Third-party modules
from configobj import configobj
from configobj import validate

# My modules
import misc

class ConfigError(Exception):
    pass

def debug_errors(config, valres):
    """Output debug info about missing sections or invalid values."""
    errors = configobj.flatten_errors(config, valres)
    for section_list, key, error in errors:
        if key is not None:
           section_list.append(key)
        else:
            section_list.append('[missing section]')
        if error == False:
            sys.stderr.write('Missing value or section.')
        section_string = ', '.join(section_list)
        sys.stderr.write("Errors on validation:\n")
        sys.stderr.write("%s = %s\n" % (section_string,error))
    return errors

def load_config(config_file, template_file, validator=None, ignore_errors=False):
    """Run all config modules."""
    if hasattr(template_file, "readlines"):
        template = template_file.readlines() 
    else: template = open(template_file).readlines()
    if validator is None:    
        validator = validate.Validator()
    config = configobj.ConfigObj(config_file, configspec=template)
    valres = config.validate(validator, preserve_errors=True)
    if valres is not True and not ignore_errors:
        errors = debug_errors(config, valres)    
        raise ConfigError(errors)
    return config
